package cn.zb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @Description:Secirity核心配置
 * @Author:
 * @Date: 2024/11/22 18:44
 */
@Configuration
@EnableWebFluxSecurity // 开启security功能
public class SecurityConfig{

    @Resource
    AuthException authException; // 认证异常类
    @Resource
    AccessException accessException; // 授权异常类
    @Resource
    TokenSecurityConfig tokenSecurityContext; // 从请求头获取身份信息实现
    // 白名单 放行数组
    String[] bai = {
            "/auth/**",
            "/flow/warm-flow-ui/**",
             "/flow/warm-flow/**",
            "/system/menu/router"
    };

    @Bean
    SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http){
        http.authorizeExchange().pathMatchers(bai).permitAll()
                .anyExchange().authenticated();

        http.exceptionHandling().authenticationEntryPoint(authException);
        http.exceptionHandling().accessDeniedHandler(accessException);
        // 从请求头获取用户身份 鉴权需要
        http.securityContextRepository(tokenSecurityContext);
        // 关闭请求跨站
        http.csrf().disable();
        // 跨域支持
        http.cors().configurationSource(configurationSource());
        return http.build();
    }

    //跨域配置
    CorsConfigurationSource configurationSource(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);
        return source;
    }

}